package jp.chiheisen.popuptail;

import jp.chiheisen.popuptail.tail.Tail;
import jp.chiheisen.popuptail.tail.TailEvent;
import jp.chiheisen.popuptail.tail.TailListener;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

public class PopupTail implements TailListener {

    /** トレイアイコン */
    private final PopupTailTrayIcon trayIcon;
    /** 監視対象のファイル */
    private final File file;
    /** 文字コード */
    private final Charset charset;
	
	public PopupTail(File file, Charset charset) throws IOException, AWTException{
        if(file == null){
            throw new NullPointerException("file");
        }
        if(charset == null){
            throw new NullPointerException("charset");
        }

        this.trayIcon = new PopupTailTrayIcon(file);
        this.file = file;
        this.charset = charset;
	}

    public void start(){
        Tail tail = new Tail(file);
        tail.addTailListener(this);

        final Thread tailThread = new Thread(tail);
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run(){
                tailThread.interrupt();
            }
        });

        tailThread.start();
    }

    @Override
    public void modify(TailEvent event) {
        String tail = new String(event.getTail(), charset);
        String[] split = tail.split("\r\n|\r|\n");

        if (split.length != 0) {
            trayIcon.displayMessage(split[split.length - 1], TrayIcon.MessageType.INFO);
        }
    }
}
